//! @Author: DengLibin
//! @Date: Create in 2023-11-01 16:15:41
//! @Description: 配置
//!

extern crate serde;
extern crate serde_yaml;


use std::fmt::Display;

use serde::{Deserialize, Serialize};

use crate::app_error::AppError;

#[derive(Debug, Serialize, Deserialize)]
pub struct AppConfig {
   pub sqlite_dir: String,   //sqlite文件夹路径、
   pub sqlite_table: String, //sqlite表名
   pub mysql_table: String,  //mysql表名
   pub mysql_url: String, //mysql连接配置 例：mysql://denglibin:denglibin@192.168.6.115:3307/crawler_data
   pub colums: Vec<String>, //字段 （sqlite和mysql要一致）
   pub batch_size: u32, //批次大小
   pub up_column: String,  //递增字段
}

// 自定义结果
type ConfigResult<T> = std::result::Result<T, AppError>;

//转换结果
fn check_result<T, E: Display>(result: Result<T, E>) -> ConfigResult<T> {
    return match result {
        Ok(r) => Result::Ok(r),
        Err(err) => Result::Err(AppError {
            msg: err.to_string(),
        }),
    };
}

/// @Author: DengLibin
/// @Date: Create in 2023-11-01 16:21:13
/// @Description: 读取文件配置
pub fn read_yaml_config(file_path: &str) -> ConfigResult<AppConfig> {
    // 使用相对路径读取 app.yaml 内容为字符串
    // let yaml_str = read_file_str(file_path)?;
    let  file = check_result(std::fs::File::open(file_path))?;
    // serde_yaml 解析字符串为 User 对象
    let config: AppConfig = check_result(serde_yaml::from_reader(file))?;
    return Ok(config);
}
